<template>
  <div class="files-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <!-- 侧边栏切换按钮 -->
        <el-button
          text
          :icon="sidebarVisible ? Menu : Menu"
          @click="toggleSidebar"
          :title="t('filesView.header.toggleSidebar')"
        />

        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumbs"
            :key="item.id"
            @click="handleBreadcrumbClick(item, index)"
            style="cursor: pointer"
          >
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="header-right">
        <!-- 搜索框 -->
        <div class="search-container">
          <el-input
            v-model="searchKeyword"
            :placeholder="t('filesView.header.searchPlaceholder')"
            style="width: 200px"
            clearable
            :loading="isSearching"
            @input="handleSearch"
            @clear="handleSearchClear"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button
            type="primary"
            text
            @click="showAdvancedSearch = true"
            :title="t('filesView.header.advancedSearch')"
            style="margin-left: 8px"
          >
            {{ t('filesView.header.advancedSearch') }}
          </el-button>
        </div>

        <!-- 排序选择 -->
        <el-select
          v-model="sortOption"
          :placeholder="t('filesView.header.sortPlaceholder')"
          style="width: 140px"
          @change="handleSortChange"
        >
          <el-option :label="t('filesView.header.sortTimeDesc')" value="time_desc" />
          <el-option :label="t('filesView.header.sortTimeAsc')" value="time_asc" />
          <el-option :label="t('filesView.header.sortNameDesc')" value="name_desc" />
          <el-option :label="t('filesView.header.sortNameAsc')" value="name_asc" />
        </el-select>

        <!-- 使用自定义文件选择器，支持分片上传 -->
        <input
          ref="fileInputRef"
          type="file"
          multiple
          :accept="acceptedFileTypes"
          style="display: none"
          @change="handleFileSelect"
        />
        <el-button
          type="primary"
          :icon="Upload"
          :loading="isUploading"
          :disabled="isUploading"
          @click="triggerFileSelect"
        >
          {{ isUploading ? t('filesView.header.uploading') : t('filesView.header.uploadButton') }}
        </el-button>
        <el-button :icon="FolderAdd" @click="handleCreateFolder">
          {{ t('filesView.header.createFolder') }}
        </el-button>
        <el-button-group>
          <el-button
            :type="viewMode === 'grid' ? 'primary' : 'default'"
            :icon="Grid"
            @click="viewMode = 'grid'"
          />
          <el-button
            :type="viewMode === 'list' ? 'primary' : 'default'"
            :icon="List"
            @click="viewMode = 'list'"
          />
        </el-button-group>

        <!-- 刷新按钮 -->
        <el-tooltip :content="t('filesView.header.refreshTooltip')" placement="bottom">
          <el-button
            text
            @click="handleRefresh"
            :icon="RefreshRight"
          >
            {{ t('filesView.header.refresh') }}
          </el-button>
        </el-tooltip>

        <!-- 快捷键帮助按钮 -->
        <el-tooltip :content="t('filesView.header.shortcutsTooltip')" placement="bottom">
          <el-button text @click="showShortcutHelp">
            <el-icon><QuestionFilled /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 侧边栏文件夹树 -->
      <div v-show="sidebarVisible" class="sidebar">
        <FolderTree
          ref="folderTreeRef"
          :current-folder-id="currentFolderId"
          @folder-click="handleFolderTreeClick"
          @folder-rename="handleFolderRename"
          @folder-delete="handleFolderDelete"
          @folder-move="handleFolderMove"
        />
      </div>

      <!-- 文件列表区域 -->
      <div class="files-container" :class="{ 'full-width': !sidebarVisible }" @click="handleContainerClick" @contextmenu.prevent="handleGlobalContextMenu">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              v-for="(item, index) in breadcrumbs"
              :key="item.id"
              :class="{ 'is-link': index < breadcrumbs.length - 1 }"
              @click="index < breadcrumbs.length - 1 && handleBreadcrumbClick(item, index)"
            >
              <el-icon v-if="index === 0"><Folder /></el-icon>
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 文件内容区域 -->
        <DragUploadArea
          :upload-path="currentFolderId"
          :disabled="isUploading"
          @files-dropped="handleDragUpload"
        >
          <div class="files-content" @click="handleContentClick" @contextmenu.prevent="handleGlobalContextMenu">
          <!-- 网格视图 -->
          <div
            v-if="viewMode === 'grid'"
            class="files-grid"
            @click="handleGridClick"
            @contextmenu.prevent="handleGlobalContextMenu"
          >
            <div
              v-for="file in files"
              :key="file.id"
              class="file-card"
              :class="{
                'selected': isFileSelected(file),
                'file-highlight': isFileHighlighted(file.id)
              }"
              :data-file-id="file.id"
              :draggable="true"
              @click="handleFileClick(file, $event)"
              @dblclick="handleFileDoubleClick(file)"
              @contextmenu.prevent="handleContextMenu(file, $event)"
              @dragstart="handleDragStart(file, $event)"
              @dragover.prevent="handleDragOver(file, $event)"
              @drop.prevent="handleDrop(file, $event)"
              @dragend="handleDragEnd"
            >
              <div class="file-icon-container" :class="getFileTypeClass(file)">
                <el-icon v-if="file.isDirectory" class="folder-icon">
                  <Folder />
                </el-icon>
                <el-icon v-else class="file-icon">
                  <component :is="getFileIcon(file.mimeType)" />
                </el-icon>
              </div>

              <div class="file-name" :title="file.originalName">{{ file.originalName }}</div>
              <div class="file-meta" v-if="!file.isDirectory">{{ formatSize(file.fileSize) }}</div>


              <div class="file-actions">
                <div class="action-buttons">
                  <el-tooltip :content="file.isFavorited ? '取消收藏' : '收藏'" placement="top">
                    <el-button
                      size="small"
                      circle
                      :icon="file.isFavorited ? StarFilled : Star"
                      @click.stop="handleToggleFavorite(file)"
                      :class="{ 'favorited': file.isFavorited }"
                    />
                  </el-tooltip>
                  <el-tooltip :content="t('filesView.contextMenu.download')" placement="top">
                    <el-button size="small" circle :icon="Download" @click.stop="handleDownload(file)" />
                  </el-tooltip>
                  <el-tooltip :content="t('filesView.contextMenu.share')" placement="top">
                    <el-button size="small" circle :icon="Share" @click.stop="handleShare(file)" />
                  </el-tooltip>
                  <el-dropdown trigger="click" @click.stop>
                    <el-button size="small" circle :icon="MoreFilled" />
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleRename(file)">
                          <el-icon><EditPen /></el-icon>
                          {{ t('filesView.contextMenu.rename') }}
                        </el-dropdown-item>
                        <el-dropdown-item divided @click="handleDelete(file)">
                          <el-icon><Delete /></el-icon>
                          {{ t('filesView.contextMenu.delete') }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="files.length === 0" class="empty-state" @contextmenu.prevent="handleGlobalContextMenu">
              <el-icon class="empty-icon"><FolderOpened /></el-icon>
              <p>{{ t('filesView.content.emptyFolder') }}</p>
              <el-button type="primary" @click="handleUpload">{{ t('filesView.content.uploadFirstFile') }}</el-button>
            </div>
          </div>

          <!-- 列表视图 -->
          <div
            v-else
            class="files-list"
            @click="handleListClick"
            @contextmenu.prevent="handleGlobalContextMenu"
          >
            <div class="list-header" @click="handleListHeaderClick">
              <div class="header-cell icon-cell"></div>
              <div class="header-cell name-cell">{{ t('filesView.content.colName') }}</div>
              <div class="header-cell size-cell">{{ t('filesView.content.colSize') }}</div>
              <div class="header-cell date-cell">{{ t('filesView.content.colModified') }}</div>
              <div class="header-cell actions-cell">{{ t('filesView.content.colActions') }}</div>
            </div>

            <div class="list-body" @click="handleListBodyClick" @contextmenu.prevent="handleGlobalContextMenu">
              <div
                v-for="file in files"
                :key="file.id"
                class="list-row"
                :class="{
                  'selected': isFileSelected(file),
                  'file-highlight': isFileHighlighted(file.id)
                }"
                :data-file-id="file.id"
                @click="handleFileClick(file, $event)"
                @dblclick="handleFileDoubleClick(file)"
                @contextmenu.prevent="handleContextMenu(file, $event)"
              >
                <div class="row-cell icon-cell">
                  <div class="file-icon-wrapper" :class="getFileTypeClass(file)">
                    <el-icon v-if="file.isDirectory" class="folder-icon">
                      <Folder />
                    </el-icon>
                    <el-icon v-else class="file-icon">
                      <component :is="getFileIcon(file.mimeType)" />
                    </el-icon>
                  </div>
                </div>

                <div class="row-cell name-cell">
                  <div class="file-name">{{ file.originalName }}</div>
                </div>

                <div class="row-cell size-cell">
                  <span v-if="!file.isDirectory" class="file-size-badge">
                    {{ formatSize(file.fileSize) }}
                  </span>
                  <span v-else class="folder-indicator">{{ t('filesView.content.folderIndicator') }}</span>
                </div>

                <div class="row-cell date-cell">
                  <span class="file-date">{{ formatDate(file.updatedAt) }}</span>
                </div>

                <div class="row-cell actions-cell">
                  <div class="list-actions">
                    <el-tooltip :content="t('filesView.contextMenu.download')" placement="top">
                      <el-button size="small" text :icon="Download" @click.stop="handleDownload(file)" />
                    </el-tooltip>
                    <el-tooltip :content="t('filesView.contextMenu.share')" placement="top">
                      <el-button size="small" text :icon="Share" @click.stop="handleShare(file)" />
                    </el-tooltip>
                    <el-dropdown trigger="click" @click.stop>
                      <el-button size="small" text :icon="MoreFilled" />
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="handleRename(file)">
                            <el-icon><EditPen /></el-icon>
                            {{ t('filesView.contextMenu.rename') }}
                          </el-dropdown-item>
                          <el-dropdown-item divided @click="handleDelete(file)">
                            <el-icon><Delete /></el-icon>
                            {{ t('filesView.contextMenu.delete') }}
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>

              <!-- 空白填充区域，用于点击取消选中 -->
              <div class="list-empty-space" @click="handleListBodyClick" @contextmenu.prevent="handleGlobalContextMenu"></div>
            </div>
          </div>
          </div>
        </DragUploadArea>

        <!-- 分页组件 - 固定在底部 -->
        <div class="pagination-container" v-if="files.length > 0 || pagination.total > 0">
          <el-pagination
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :page-sizes="[20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 右键菜单 -->
      <div
        v-if="contextMenuVisible"
        class="context-menu"
        :style="{
          left: contextMenuPosition.x + 'px',
          top: contextMenuPosition.y + 'px'
        }"
        @click.stop
      >
        <!-- 文件右键菜单 -->
        <template v-if="contextMenuFile">
          <div class="context-menu-item" @click="handleDownload(contextMenuFile); contextMenuVisible = false">
            <el-icon><Download /></el-icon>
            {{ t('filesView.contextMenu.download') }}
          </div>
          <div class="context-menu-item" @click="handleShare(contextMenuFile); contextMenuVisible = false">
            <el-icon><Share /></el-icon>
            {{ t('filesView.contextMenu.share') }}
          </div>
          <div class="context-menu-divider"></div>
          <div class="context-menu-item" @click="handleContextCopy(contextMenuFile); contextMenuVisible = false">
            <el-icon><CopyDocument /></el-icon>
            {{ t('filesView.contextMenu.copy') }}
          </div>
          <div class="context-menu-item" @click="handleContextCut(contextMenuFile); contextMenuVisible = false">
            <el-icon><Scissor /></el-icon>
            {{ t('filesView.contextMenu.cut') }}
          </div>
          <div class="context-menu-item"
               :class="{ disabled: clipboardFiles.length === 0 }"
               @click="clipboardFiles.length > 0 && handlePasteShortcut(); contextMenuVisible = false">
            <el-icon><DocumentCopy /></el-icon>
            {{ clipboardFiles.length > 0 ? t('filesView.contextMenu.pasteItems', { count: clipboardFiles.length }) : t('filesView.contextMenu.paste') }}
          </div>
          <div class="context-menu-divider"></div>
          <div class="context-menu-item" @click="handleRename(contextMenuFile); contextMenuVisible = false">
            <el-icon><EditPen /></el-icon>
            {{ t('filesView.contextMenu.rename') }}
          </div>
          <div class="context-menu-divider"></div>
          <div class="context-menu-item danger" @click="handleDelete(contextMenuFile); contextMenuVisible = false">
            <el-icon><Delete /></el-icon>
            {{ t('filesView.contextMenu.delete') }}
          </div>
        </template>

        <!-- 空白区域右键菜单 -->
        <template v-else>
          <div class="context-menu-item"
               :class="{ disabled: clipboardFiles.length === 0 }"
               @click="clipboardFiles.length > 0 && handlePasteShortcut(); contextMenuVisible = false">
            <el-icon><DocumentCopy /></el-icon>
            {{ clipboardFiles.length > 0 ? t('filesView.contextMenu.pasteItems', { count: clipboardFiles.length }) : t('filesView.contextMenu.paste') }}
          </div>
          <div class="context-menu-divider"></div>
          <div class="context-menu-item" @click="handleCreateFolder(); contextMenuVisible = false">
            <el-icon><FolderAdd /></el-icon>
            {{ t('filesView.contextMenu.createFolder') }}
          </div>
        </template>
      </div>
    </div>

    <!-- 高级搜索对话框 -->
    <AdvancedSearch
      v-model="showAdvancedSearch"
      :current-folder-id="currentFolderId"
      @search="handleAdvancedSearch"
    />

    <!-- 文件预览组件 -->
    <FilePreview
      :visible="previewVisible"
      :file-id="previewFile?.id || 0"
      :file-name="previewFile?.originalName || ''"
      :mime-type="previewFile?.mimeType || ''"
      :file-size="previewFile?.fileSize || 0"
      @update:visible="previewVisible = $event"
      @close="closeFilePreview"
      @download="handleFileDownload"
    />

    <!-- 文件分享对话框 -->
    <ShareDialog
      :visible="shareDialogVisible"
      :file-info="selectedFileForShare"
      @update:visible="shareDialogVisible = $event"
      @share-created="handleShareCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted,onUnmounted, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { useAuthStore } from '@/stores/auth'
import {
  Upload, FolderAdd, Grid, List, Folder, FolderOpened,
  Download, Share, Delete, MoreFilled, Search, Menu, QuestionFilled, RefreshLeft, RefreshRight,
  CopyDocument, Scissor, DocumentCopy, EditPen, Star, StarFilled
} from '@element-plus/icons-vue'
import * as fileApi from '@/api/modules/file'
import { folderApi } from '@/api/modules/folder'
import { favoriteApi } from '@/api/favorite'
import request from '@/api/request'
import { useFileManagerShortcuts } from '../../composables/useKeyboardShortcuts'
import { useFileUpload } from '@/composables/useFileUpload'
import { useFileDownload } from '@/composables/useFileDownload'
import { validateFileSize, validateFileType, formatFileSize } from '@/config/upload'
import AdvancedSearch from '@/components/business/AdvancedSearch.vue'
// 启用文件夹树组件
import FolderTree from '@/components/business/FolderTree.vue'
import FilePreview from '@/components/business/FilePreview.vue'
import ShareDialog from '@/components/business/ShareDialog.vue'
import DragUploadArea from '@/components/upload/DragUploadArea.vue'

const { t } = useI18n()

// 简单的类型定义
interface FileInfo {
  id: number
  fileName: string
  originalName: string
  fileSize: number
  mimeType?: string
  isDirectory: boolean
  parentId?: number
  ownerId: number
  createdAt: string
  updatedAt: string
}

interface BreadcrumbItem {
  id: number
  name: string
  parentId?: number
}

// 视图模式
const viewMode = ref<'grid' | 'list'>('grid')

// 文件视图偏好设置存储
const STORAGE_KEY = 'files-view-preferences'

/**
 * 保存文件视图偏好设置
 */
const saveViewPreferences = () => {
  try {
    const preferences = {
      viewMode: viewMode.value,
      updatedAt: Date.now()
    }
    localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences))
    // console.log('文件视图偏好设置已保存:', preferences)
  } catch (error) {
    // console.warn('保存文件视图偏好设置失败:', error)
  }
}

/**
 * 加载文件视图偏好设置
 */
const loadViewPreferences = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY)
    if (saved) {
      const preferences = JSON.parse(saved)
      if (preferences.viewMode && ['grid', 'list'].includes(preferences.viewMode)) {
        viewMode.value = preferences.viewMode
        // console.log('文件视图偏好设置已加载:', preferences)
      }
    }
  } catch (error) {
    // console.warn('加载文件视图偏好设置失败:', error)
  }
}

// 侧边栏控制
const sidebarVisible = ref(true)
const folderTreeRef = ref()

// 响应式侧边栏控制
const checkScreenSize = () => {
  const screenWidth = window.innerWidth
  // 在小屏幕上默认隐藏侧边栏
  if (screenWidth <= 768) {
    sidebarVisible.value = false
  } else {
    sidebarVisible.value = true
  }
}

// 监听窗口大小变化
const handleResize = () => {
  checkScreenSize()
}

// 监听视图模式变化并自动保存
watch(viewMode, () => {
  saveViewPreferences()
})

onMounted(() => {
  // 加载文件视图偏好设置
  loadViewPreferences()

  checkScreenSize()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
// const uploadRef = ref() // 已移除，使用分片上传

// 上传队列管理（使用分片上传，移除旧的状态管理）
// const uploadQueue = ref<File[]>([])
// const isUploading = ref(false)
// const currentUploadIndex = ref(0)

// 面包屑导航
const breadcrumbs = ref<BreadcrumbItem[]>([
  { id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined }
])

const handleBreadcrumbClick = (item: BreadcrumbItem, index: number) => {
  // 设置当前文件夹ID
  currentFolderId.value = item.id === 0 ? undefined : item.id

  // 截断面包屑到点击的位置
  breadcrumbs.value = breadcrumbs.value.slice(0, index + 1)

  // 重新加载文件列表
  setTimeout(() => loadFiles(), 0)
}

// 文件列表
const files = ref<FileInfo[]>([])
const highlightFileId = ref<number | null>(null) // 需要高亮的文件ID

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 文件选中状态管理 - 提前声明
const selectedFiles = ref<FileInfo[]>([])
const lastSelectedFile = ref<FileInfo | null>(null)

// 文件预览相关
const previewVisible = ref(false)
const previewFile = ref<FileInfo | null>(null)

// 文件分享相关
const shareDialogVisible = ref(false)
const selectedFileForShare = ref<FileInfo | null>(null)

// 使用分片上传组合式函数
const {
  isUploading,
  uploadProgress,
  uploadFiles,
  uploadSingleFile: uploadSingleFileChunk
} = useFileUpload()

// 使用文件下载组合式函数
const {
  downloadFileWithProgress,
  getAllSessions: getAllDownloadSessions
} = useFileDownload()

// 拖拽上传处理
const handleDragUpload = async (files: File[], uploadPath?: number) => {
  try {
    // 使用传入的uploadPath或当前文件夹ID
    const targetFolderId = uploadPath || currentFolderId.value

    // 检查存储配额（与普通上传保持一致）
    try {
      const statsResponse = await fileApi.getStorageStats()
      const totalFileSize = files.reduce((sum, file) => sum + file.size, 0)

      if (statsResponse.data.availableSpace < totalFileSize) {
        ElMessage.error(t('filesView.messages.storageQuotaExceeded', { needed: formatSize(totalFileSize), available: formatSize(statsResponse.data.availableSpace) }))
        return
      }
    } catch (error) {
      // 静默处理存储状态检查失败，继续上传
    }

    // 文件验证（与普通上传保持一致）
    const invalidFiles: string[] = []
    const largeFiles: string[] = []

    for (const file of files) {
      // 文件大小验证
      const sizeValidation = validateFileSize(file)
      if (!sizeValidation.valid) {
        invalidFiles.push(sizeValidation.message!)
        continue
      }
      if (sizeValidation.isLarge) {
        largeFiles.push(file.name)
      }

      // 文件类型验证
      const typeValidation = validateFileType(file)
      if (!typeValidation.valid) {
        invalidFiles.push(typeValidation.message!)
      }
    }

    // 显示验证结果
    if (invalidFiles.length > 0) {
      ElMessage.error(invalidFiles.join('; '))
      return
    }

    // 简化提示：只在有大文件时显示一次提示
    const hasLargeFiles = files.some(file => file.size > 100 * 1024 * 1024) // 100MB
    if (hasLargeFiles) {
      ElMessage.info('正在处理大文件，请稍候...')
    }

    // 调用现有的文件上传逻辑
    await uploadFiles(files, targetFolderId)

    // 上传完成后刷新文件列表
    await loadFiles()

    // 使用系统通知而不是Element Plus提示
    if (window.electronAPI) {
      // Electron环境：使用系统通知
      window.electronAPI.notification.show({
        title: 'RickPan',
        body: `成功上传 ${files.length} 个文件`,
        icon: '/favicon.ico'
      })
    } else {
      // Web环境：使用浏览器通知API
      if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('RickPan', {
          body: `成功上传 ${files.length} 个文件`,
          icon: '/favicon.ico'
        })
      } else if ('Notification' in window && Notification.permission !== 'denied') {
        // 请求通知权限
        Notification.requestPermission().then(permission => {
          if (permission === 'granted') {
            new Notification('RickPan', {
              body: `成功上传 ${files.length} 个文件`,
              icon: '/favicon.ico'
            })
          }
        })
      } else {
        // 降级到Element Plus提示
        ElMessage.success(`成功上传 ${files.length} 个文件`)
      }
    }
  } catch (error) {
    ElMessage.error(t('filesView.messages.uploadFailed', { message: (error as Error).message }))
  }
}

// 文件选择相关
const fileInputRef = ref<HTMLInputElement>()
const acceptedFileTypes = '*' // 接受所有文件类型

// 触发文件选择
const triggerFileSelect = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 处理文件选择
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = Array.from(target.files || [])

  if (files.length === 0) return

  // 检查存储配额
  try {
    const statsResponse = await fileApi.getStorageStats()
    const totalFileSize = files.reduce((sum, file) => sum + file.size, 0)

    if (statsResponse.data.availableSpace < totalFileSize) {
      ElMessage.error(t('filesView.messages.storageQuotaExceeded', { needed: formatSize(totalFileSize), available: formatSize(statsResponse.data.availableSpace) }))
      target.value = ''
      return
    }
  } catch (error) {
    // 静默处理存储状态检查失败，继续上传
  }

  // 文件验证
  const invalidFiles: string[] = []
  const largeFiles: string[] = []

  for (const file of files) {
    // 文件大小验证
    const sizeValidation = validateFileSize(file)
    if (!sizeValidation.valid) {
      invalidFiles.push(sizeValidation.message!)
      continue
    }
    if (sizeValidation.isLarge) {
      largeFiles.push(file.name)
    }

    // 文件类型验证
    const typeValidation = validateFileType(file)
    if (!typeValidation.valid) {
      invalidFiles.push(typeValidation.message!)
    }
  }

  // 显示验证结果
  if (invalidFiles.length > 0) {
    ElMessage.error(invalidFiles.join('; '))
    target.value = ''
    return
  }

  try {
    // 使用分片上传
    const results = await uploadFiles(files, currentFolderId.value || undefined)

    // 上传完成后刷新文件列表
    await loadFiles()
    ElMessage.success(t('filesView.messages.uploadSuccess', { count: files.length }))

  } catch (error) {
    ElMessage.error(t('filesView.messages.uploadFailed', { message: (error as Error).message }))
  } finally {
    // 清空文件选择
    if (target) {
      target.value = ''
    }
  }
}

// 文件选中逻辑
const isFileSelected = (file: FileInfo) => {
  return selectedFiles.value.some(f => f.id === file.id)
}

const selectFile = (file: FileInfo, multiSelect = false) => {
  if (multiSelect) {
    // 多选模式
    if (isFileSelected(file)) {
      // 取消选中
      selectedFiles.value = selectedFiles.value.filter(f => f.id !== file.id)
    } else {
      // 添加到选中列表
      selectedFiles.value.push(file)
    }
  } else {
    // 单选模式
    selectedFiles.value = [file]
  }
  lastSelectedFile.value = file
}

const clearSelection = () => {
  selectedFiles.value = []
  lastSelectedFile.value = null
}

// 加载文件列表 - 提前声明
const loadFiles = async () => {
  try {
    // 解析排序参数
    const [orderBy, orderDirection] = sortOption.value.split('_')
    const orderField = orderBy === 'time' ? 'updatedAt' : 'fileName'

    // 调用API获取文件列表
    const searchParam = searchKeyword.value || undefined

    const response = await fileApi.getFileList({
      parentId: currentFolderId.value,
      page: pagination.value.currentPage - 1, // 后端从0开始
      size: pagination.value.pageSize,
      orderBy: orderField,
      orderDirection: orderDirection as 'asc' | 'desc',
      search: searchParam
    })

    // API封装返回的是ApiResponse，需要访问data字段
    const data = response.data
    files.value = data.content || []
    // 更新分页信息
    pagination.value.total = data.totalElements || 0

    // 检查文件收藏状态
    await checkFavoriteStatus()

    // 如果有需要高亮的文件，在文件列表加载后触发高亮
    if (highlightFileId.value) {
      setTimeout(() => {
        scrollToHighlightFile(highlightFileId.value!)
      }, 100)
    }
  } catch (error: any) {
    if (error.response) {
      // 服务器返回了错误状态码
      ElMessage.error(t('filesView.messages.getListFailed', { status: error.response.status }))
    } else if (error.request) {
      // 请求发出但没有收到响应
      ElMessage.error(t('filesView.messages.networkError'))
    } else {
      // 其他错误
      ElMessage.error(t('filesView.messages.getListFailedGeneral'))
    }
    files.value = []
  } finally {
    // 重置搜索状态
    isSearching.value = false
  }
}

// 搜索和排序
const searchKeyword = ref('')
const sortOption = ref('time_desc')
const showAdvancedSearch = ref(false)
const currentSearchParams = ref(null)

// 复制粘贴状态
const clipboardFiles = ref<any[]>([])
const clipboardOperation = ref<'copy' | 'cut' | null>(null)

// 当前文件夹
const currentFolderId = ref<number | undefined>(undefined)

// 获取token
const getToken = () => {
  let token = localStorage.getItem('token') || ''

  // 如果没有token，创建一个临时的测试token
  if (!token) {
    token = 'test-token-for-development'
    localStorage.setItem('token', token)
    console.log('创建临时测试token')
  }

  console.log('当前token:', token ? '存在' : '不存在')
  return token
}

// 旧的获取上传数据方法（已移除，使用分片上传）
/*
const getUploadData = () => {
  if (currentFolderId.value) {
    return { parentId: currentFolderId.value }
  }
  return {}
}
*/

// 旧的上传处理函数（已移除，使用分片上传）
/*
const handleUploadSuccess = (response: any, file: any) => { ... }
const handleUploadError = (error: any, file: any) => { ... }
const handleUploadExceed = () => { ... }
*/

// 旧的文件选择处理方法（已移除，使用分片上传）
// const handleUploadChange = (file: any, fileList: any[]) => {
//   // 已替换为 handleFileSelect 方法
// }

// 旧的上传前验证方法（已移除，使用分片上传）
/*
const handleBeforeUpload = (file: any) => {
  // 文件验证逻辑已移至 handleFileSelect 中
  return false
}
*/

// 旧的队列上传方法（已移除，使用分片上传）
/*
const startQueueUpload = async () => {
  // 已替换为 handleFileSelect 中的分片上传逻辑
}
*/

// 旧的单文件上传函数（已移除，使用分片上传）
/*
const uploadSingleFile = async (file: File): Promise<void> => {
  // 已替换为分片上传逻辑
}
*/

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  loadFiles()
}

const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page
  loadFiles()
}

// 搜索处理 - 添加防抖
let searchTimer: any = null
const isSearching = ref(false)

const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  if (!searchKeyword.value.trim()) {
    handleSearchClear()
    return
  }

  isSearching.value = true
  searchTimer = setTimeout(() => {
    pagination.value.currentPage = 1
    loadFiles()
  }, 500) // 500ms防抖
}

const handleSearchClear = () => {
  searchKeyword.value = ''
  isSearching.value = false
  currentSearchParams.value = null
  pagination.value.currentPage = 1
  loadFiles()
}

// 高级搜索处理
const handleAdvancedSearch = async (searchParams: any) => {
  try {
    isSearching.value = true
    currentSearchParams.value = searchParams
    pagination.value.currentPage = 1

    console.log('高级搜索参数:', searchParams)

    // 调用高级搜索API
    await performAdvancedSearch(searchParams)

    ElMessage.success(t('filesView.messages.searchComplete'))
  } catch (error) {
    console.error('高级搜索失败:', error)
    ElMessage.error(t('filesView.messages.searchFailed'))
  } finally {
    isSearching.value = false
  }
}

// 执行高级搜索
const performAdvancedSearch = async (searchParams: any) => {
  try {
    // 构建搜索请求参数
    const params: any = {
      page: pagination.value.currentPage - 1,
      size: pagination.value.pageSize
    }

    // 添加搜索条件
    if (searchParams.fileName) {
      params.fileName = searchParams.fileName
    }

    if (searchParams.fileType && searchParams.fileType.length > 0) {
      params.fileTypes = searchParams.fileType.join(',')
    }

    if (searchParams.minSize !== undefined || searchParams.maxSize !== undefined) {
      // 转换文件大小单位为字节
      const unitMap: { [key: string]: number } = {
        'KB': 1024,
        'MB': 1024 * 1024,
        'GB': 1024 * 1024 * 1024
      }
      const unitMultiplier = unitMap[searchParams.sizeUnit] || 1024 * 1024

      if (searchParams.minSize !== undefined) {
        params.minSize = searchParams.minSize * unitMultiplier
      }
      if (searchParams.maxSize !== undefined) {
        params.maxSize = searchParams.maxSize * unitMultiplier
      }
    }

    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.startDate = searchParams.dateRange[0]
      params.endDate = searchParams.dateRange[1]
    }

    if (searchParams.searchScope === 'folder' && searchParams.targetFolderId) {
      params.parentId = searchParams.targetFolderId
    } else if (searchParams.searchScope === 'current') {
      params.parentId = currentFolderId.value
    }
    // 'all' 搜索不设置parentId

    // 添加排序参数
    if (searchParams.sortBy) {
      const [orderBy, orderDirection] = searchParams.sortBy.includes('_')
        ? searchParams.sortBy.split('_')
        : [searchParams.sortBy, 'desc']

      params.orderBy = orderBy === 'time' ? 'updatedAt' :
                      orderBy === 'name' ? 'fileName' :
                      orderBy === 'size' ? 'fileSize' : 'relevance'
      params.orderDirection = orderDirection
    }

    console.log('发送高级搜索请求:', params)

    // 调用后端高级搜索API
    const response = await fileApi.advancedSearch(params)

    // API封装已处理响应状态，直接使用数据
    const data = response.data
    files.value = data.content || []
    pagination.value.total = data.totalElements || 0

    console.log('高级搜索结果:', files.value.length, '个文件')

    // 如果有搜索结果，显示搜索结果提示
    if (files.value.length > 0) {
      ElMessage.success(t('filesView.messages.advancedSearchFound', { count: files.value.length }))
    } else {
      ElMessage.info(t('filesView.messages.advancedSearchNotFound'))
    }
  } catch (error: any) {
    console.error('高级搜索失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error(t('filesView.messages.searchServiceUnavailable'))
    } else {
      ElMessage.error(error.message || t('filesView.messages.searchFailed'))
    }
    files.value = []
    pagination.value.total = 0
  }
}

// 排序处理
const handleSortChange = () => {
  pagination.value.currentPage = 1
  loadFiles()
}

// 其他处理函数
const handleUpload = () => {
  // 直接触发上传功能
  const uploadInput = document.querySelector('.el-upload input[type="file"]') as HTMLInputElement
  if (uploadInput) {
    uploadInput.click()
  } else {
    ElMessage.error(t('filesView.messages.uploadFeatureUnavailable'))
  }
}

const handleCreateFolder = () => {
  ElMessageBox.prompt(t('filesView.dialogs.createFolderPrompt'), t('filesView.dialogs.createFolderTitle'), {
    confirmButtonText: t('filesView.contextMenu.createFolder'),
    cancelButtonText: t('filesView.dialogs.cancel'),
    inputPattern: /^[^\\/:*?"<>|]+$/,
    inputErrorMessage: t('filesView.messages.invalidFolderName')
  }).then(async ({ value }) => {
    try {
      const createFolderData: any = { folderName: value }
      if (currentFolderId.value) {
        createFolderData.parentId = currentFolderId.value
      }
      const response = await fileApi.createFolder(createFolderData)

      // API封装已处理响应状态，直接使用数据
      ElMessage.success(t('filesView.messages.createFolderSuccess', { name: value }))
      // 刷新文件列表
      setTimeout(() => loadFiles(), 0)
    } catch (error) {
      console.error('创建文件夹失败:', error)
      ElMessage.error(t('filesView.messages.createFolderFailed'))
    }
  }).catch(() => {
    // 用户取消
  })
}

// 右键菜单
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const contextMenuFile = ref<FileInfo | null>(null)

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 获取文件图标
const getFileIcon = (mimeType?: string) => {
  if (!mimeType) return 'Document'

  if (mimeType.startsWith('image/')) return 'Picture'
  if (mimeType.startsWith('video/')) return 'VideoPlay'
  return 'Document'
}

// 获取文件类型样式类
const getFileTypeClass = (file: FileInfo) => {
  if (file.isDirectory) return 'folder-preview'
  if (!file.mimeType && !file.originalName) return 'document-preview'

  if (file.mimeType?.startsWith('image/')) return 'image-preview'
  if (file.mimeType?.startsWith('video/')) return 'video-preview'
  if (file.mimeType?.includes('pdf') || file.originalName?.toLowerCase().endsWith('.pdf')) return 'pdf-preview'
  return 'document-preview'
}

// 文件操作
// 文件操作函数已移到下方

const handleFileClick = (file: FileInfo, event?: MouseEvent) => {
  // 阻止事件冒泡，避免触发空白区域点击
  event?.stopPropagation()

  // 检查是否按住Ctrl键进行多选
  const multiSelect = event?.ctrlKey || event?.metaKey || false

  selectFile(file, multiSelect)

  if (file.isDirectory) {
    // console.log('选中文件夹:', file.originalName)
  } else {
    // console.log('选中文件:', file.originalName)
  }
}

const handleFileDoubleClick = (file: FileInfo) => {
  if (file.isDirectory) {
    // 双击文件夹：进入文件夹
    currentFolderId.value = file.id
    // 更新面包屑导航 - 添加当前文件夹到面包屑
    breadcrumbs.value.push({
      id: file.id,
      name: file.originalName,
      parentId: file.parentId
    })
    // 重新加载文件列表
    setTimeout(() => loadFiles(), 0)
    // ElMessage.info(`进入文件夹: ${file.originalName}`)
  } else {
    // 双击文件：进行预览（支持图片、PDF、视频）
    if (file.mimeType?.startsWith('image/') ||
        file.mimeType === 'application/pdf' ||
        file.originalName?.toLowerCase().endsWith('.pdf') ||
        file.mimeType?.startsWith('video/')) {
      handlePreview(file)
    } else {
      // 其他文件双击提示用户
      ElMessage.info(t('filesView.messages.previewNotSupported', { name: file.originalName }))
      console.log('双击文件:', file.originalName)
    }
  }
}

const handlePreview = async (file: FileInfo) => {
  if (file.mimeType?.startsWith('image/')) {
    // 图片预览 - 使用FilePreview组件
    openFilePreview(file)
  } else if (file.mimeType === 'application/pdf' || file.originalName?.toLowerCase().endsWith('.pdf')) {
    // PDF预览 - 使用FilePreview组件（支持MIME类型检测和文件扩展名检测）
    openFilePreview(file)
  } else if (file.mimeType?.startsWith('video/')) {
    // 视频预览 - 使用FilePreview组件
    openFilePreview(file)
  } else {
    console.log('不支持预览的文件类型:', file.mimeType, '文件名:', file.originalName)
    ElMessage.info(t('filesView.messages.previewNotSupported', { name: file.originalName }))
  }
}

// 打开文件预览
const openFilePreview = (file: FileInfo) => {
  previewFile.value = file
  previewVisible.value = true
}

// 关闭文件预览
const closeFilePreview = () => {
  previewVisible.value = false
  previewFile.value = null
}

// 处理文件下载
const handleFileDownload = (fileId: number) => {
  // 这里可以添加下载逻辑
  console.log('下载文件:', fileId)
}

const handleContextMenu = (file: FileInfo, event: MouseEvent) => {
  event.preventDefault()
  event.stopPropagation()

  // 选中右键的文件
  selectFile(file, false)

  contextMenuFile.value = file

  // 计算菜单位置，考虑边界检测
  const menuWidth = 200 // 预估菜单宽度
  const menuHeight = 300 // 预估菜单高度

  let x = event.clientX
  let y = event.clientY

  // 右边界检测
  if (x + menuWidth > window.innerWidth) {
    x = window.innerWidth - menuWidth - 10
  }

  // 下边界检测
  if (y + menuHeight > window.innerHeight) {
    y = window.innerHeight - menuHeight - 10
  }

  // 确保不超出左上边界
  x = Math.max(10, x)
  y = Math.max(10, y)

  contextMenuPosition.value = { x, y }
  contextMenuVisible.value = true

  // 点击其他地方关闭菜单
  const closeMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', closeMenu)
  }

  setTimeout(() => {
    document.addEventListener('click', closeMenu)
  }, 100)
}

// 全局右键菜单处理（用于空白区域）
const handleGlobalContextMenu = (event: MouseEvent) => {
  console.log('🔍 全局右键菜单事件触发', {
    target: (event.target as HTMLElement).className,
    currentTarget: (event.currentTarget as HTMLElement).className,
    tagName: (event.target as HTMLElement).tagName
  })

  // 检查是否点击在文件项上，如果是则不处理
  const target = event.target as HTMLElement
  const isFileItem = target.closest('.file-card') || target.closest('.list-row')

  console.log('📋 文件项检查:', {
    isFileItem: !!isFileItem,
    fileCard: !!target.closest('.file-card'),
    listRow: !!target.closest('.list-row')
  })

  if (!isFileItem) {
    event.preventDefault()
    event.stopPropagation()

    console.log('🖱️ 全局右键菜单触发 - 空白区域', {
      target: target.className,
      clientX: event.clientX,
      clientY: event.clientY
    })

    // 显示全局右键菜单（只有粘贴选项）
    contextMenuFile.value = null

    // 计算菜单位置，考虑边界检测
    const menuWidth = 200 // 预估菜单宽度
    const menuHeight = 150 // 全局菜单较小

    let x = event.clientX
    let y = event.clientY

    // 右边界检测
    if (x + menuWidth > window.innerWidth) {
      x = window.innerWidth - menuWidth - 10
    }

    // 下边界检测
    if (y + menuHeight > window.innerHeight) {
      y = window.innerHeight - menuHeight - 10
    }

    // 确保不超出左上边界
    x = Math.max(10, x)
    y = Math.max(10, y)

    contextMenuPosition.value = { x, y }
    contextMenuVisible.value = true

    // 点击其他地方关闭菜单
    const closeMenu = () => {
      // console.log('❌ 关闭全局右键菜单')
      contextMenuVisible.value = false
      document.removeEventListener('click', closeMenu)
    }

    setTimeout(() => {
      document.addEventListener('click', closeMenu)
    }, 100)
  } else {
    // console.log('🚫 点击在文件项上，不显示全局右键菜单')
  }
}

const handleDownload = async (file: FileInfo) => {
  if (file.isDirectory) {
    ElMessage.warning(t('filesView.messages.downloadFolderNotSupported'))
    return
  }

  try {
    // 使用新的下载进度功能
    await downloadFileWithProgress(file.id, file.originalName, file.fileSize)

    // 提示用户可以在传输列表中查看下载进度
    ElMessage.info(`开始下载: ${file.originalName}，可在传输列表中查看进度`)

  } catch (error: any) {
    console.error('下载失败:', error)
    if (error.message?.includes('403')) {
      ElMessage.error(t('filesView.messages.downloadFailedUnauthorized'))
    } else if (error.message?.includes('404')) {
      ElMessage.error(t('filesView.messages.downloadFailedNotFound'))
    } else {
      ElMessage.error(t('filesView.messages.downloadFailedGeneral', { message: error.message || '未知错误' }))
    }
  }
}

const handleShare = (file: FileInfo) => {
  if (file.isDirectory) {
    ElMessage.warning(t('filesView.messages.shareFolderNotSupported'))
    return
  }

  selectedFileForShare.value = file
  shareDialogVisible.value = true
}

const handleShareCreated = (shareData: any) => {
  console.log('分享创建成功:', shareData)
  ElMessage.success(t('filesView.messages.shareCreatedSuccess', { name: shareData.fileName }))
}

// 收藏功能
const checkFavoriteStatus = async () => {
  try {
    // 批量检查文件收藏状态
    for (const file of files.value) {
      try {
        const isFavorited = await favoriteApi.checkFavorite(file.id)
        file.isFavorited = isFavorited
      } catch (error) {
        // 如果检查失败，默认为未收藏
        file.isFavorited = false
      }
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

const handleToggleFavorite = async (file: FileInfo) => {
  try {
    if (file.isFavorited) {
      // 取消收藏
      await favoriteApi.removeFavorite(file.id)
      file.isFavorited = false
      ElMessage.success(`已取消收藏 ${file.originalName}`)
    } else {
      // 添加收藏
      await favoriteApi.addFavorite({
        fileId: file.id,
        itemType: file.isDirectory ? 'folder' : 'file',
        category: 'default',
        notes: ''
      })
      file.isFavorited = true
      ElMessage.success(`已收藏 ${file.originalName}`)
    }
  } catch (error: any) {
    console.error('收藏操作失败:', error)
    ElMessage.error(error.message || '收藏操作失败')
  }
}

const handleRename = (file: FileInfo) => {
  // 重命名文件
  ElMessageBox.prompt(t('filesView.dialogs.renamePrompt'), t('filesView.dialogs.renameTitle'), {
    confirmButtonText: t('filesView.contextMenu.rename'),
    cancelButtonText: t('filesView.dialogs.cancel'),
    inputValue: file.originalName,
    inputPattern: /^[^\\/:*?"<>|]+$/,
    inputErrorMessage: t('filesView.messages.invalidFileName')
  }).then(async ({ value }) => {
    try {
      // API封装已处理响应状态，直接使用
      await fileApi.renameFile(file.id, { newName: value })

      ElMessage.success(t('filesView.messages.renameSuccess'))
      setTimeout(() => loadFiles(), 0)
    } catch (error) {
      console.error('重命名失败:', error)
      ElMessage.error(t('filesView.messages.renameFailed'))
    }
  }).catch(() => {
    // 用户取消
  })
}

const handleDelete = (file: FileInfo) => {
  ElMessageBox.confirm(
    t('filesView.dialogs.deletePrompt', { name: file.originalName }),
    t('filesView.dialogs.deleteTitle'),
    {
      confirmButtonText: t('filesView.contextMenu.delete'),
      cancelButtonText: t('filesView.dialogs.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      // API封装已处理响应状态，直接使用
      await fileApi.deleteFile(file.id)

      ElMessage.success(t('filesView.messages.deleteSuccess'))
      // 刷新用户信息以更新存储空间
      try {
        await refreshUserStorageInfo()
      } catch (error) {
        console.warn('刷新用户存储信息失败:', error)
      }
      setTimeout(() => loadFiles(), 0)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(t('filesView.messages.deleteFailed'))
    }
  }).catch(() => {
    // 用户取消
  })
}

// 侧边栏控制
const toggleSidebar = () => {
  sidebarVisible.value = !sidebarVisible.value
}

// 刷新功能
const handleRefresh = () => {
  loadFiles()
}





// 点击空白区域取消选中
const handleGridClick = (event: MouseEvent) => {
  // 检查点击的是否是网格容器本身，而不是文件项
  if (event.target === event.currentTarget) {
    clearSelection()
  }
}

const handleListClick = (event: MouseEvent) => {
  // 检查点击的是否是列表容器本身，而不是文件项
  if (event.target === event.currentTarget) {
    clearSelection()
  }
}


const handleListBodyClick = (event: MouseEvent) => {
  // 检查点击的是否是列表主体本身，而不是文件行
  if (event.target === event.currentTarget) {
    clearSelection()
    // 点击列表主体空白区域，清除选择
  }
}

const handleListHeaderClick = (event: MouseEvent) => {
  // 点击列表头部区域取消选中
  clearSelection()
  // 点击列表头部区域，清除选择
}

const handleContainerClick = (event: MouseEvent) => {
  // 检查点击的是否是容器本身，而不是子元素
  if (event.target === event.currentTarget) {
    clearSelection()
    // 点击文件容器空白区域，清除选择
  }
}

const handleContentClick = (event: MouseEvent) => {
  // 检查点击的是否是内容区域本身，而不是子元素
  if (event.target === event.currentTarget) {
    clearSelection()
    // 点击文件内容空白区域，清除选择
  }
}



// 快捷键处理函数
const handleUploadShortcut = () => {
  // 触发上传按钮点击
  const uploadButton = document.querySelector('.el-upload input') as HTMLInputElement
  if (uploadButton) {
    uploadButton.click()
  }
}

const handleCreateFolderShortcut = () => {
  handleCreateFolder()
}

const handleRefreshShortcut = () => {
  loadFiles()
  ElMessage.success(t('filesView.messages.refreshed'))
}

const handleSelectAllShortcut = () => {
  if (selectedFiles.value.length === files.value.length) {
    // 如果已全选，则取消全选
    clearSelection()
  } else {
    // 全选所有文件
    selectedFiles.value = [...files.value]
  }
}

const handleDeleteShortcut = () => {
  if (selectedFiles.value.length > 0) {
    const firstSelected = selectedFiles.value[0]
    handleDelete(firstSelected)
  }
}

const handlePreviewShortcut = () => {
  if (selectedFiles.value.length > 0) {
    const firstSelected = selectedFiles.value[0]
    handlePreview(firstSelected)
  }
}

const handleDownloadShortcut = () => {
  if (selectedFiles.value.length > 0) {
    const firstSelected = selectedFiles.value[0]
    handleDownload(firstSelected)
  }
}

const handleRenameShortcut = () => {
  if (selectedFiles.value.length > 0) {
    const firstSelected = selectedFiles.value[0]
    handleRename(firstSelected)
  }
}

const handleSearchShortcut = () => {
  // 聚焦到搜索框
  const searchInput = document.querySelector('.el-input__inner') as HTMLInputElement
  if (searchInput) {
    searchInput.focus()
  }
}

const handleToggleViewShortcut = () => {
  viewMode.value = viewMode.value === 'grid' ? 'list' : 'grid'
}

const handleToggleSidebarShortcut = () => {
  toggleSidebar()
}

const handleEscapeShortcut = () => {
  // 清除选择
  clearSelection()
  // 清除搜索
  searchKeyword.value = ''
  handleSearchClear()
  // 清除剪贴板
  clipboardFiles.value = []
  clipboardOperation.value = null
}

// 复制文件
const handleCopyShortcut = () => {
  if (selectedFiles.value.length === 0) {
    return
  }

  clipboardFiles.value = [...selectedFiles.value]
  clipboardOperation.value = 'copy'
}

// 剪切文件 - 重构后的简化实现（只标记，粘贴时移动）
const handleCutShortcut = () => {
  if (selectedFiles.value.length === 0) {
    return
  }

  clipboardFiles.value = [...selectedFiles.value]
  clipboardOperation.value = 'cut'
}



// 粘贴文件
const handlePasteShortcut = async () => {
  if (clipboardFiles.value.length === 0) {
    return
  }

  try {
    const operation = clipboardOperation.value

    // 执行粘贴操作 - 逐个调用简化的API
    for (const file of clipboardFiles.value) {
      if (operation === 'copy') {
        await copyFileToCurrentFolder(file)
      } else if (operation === 'cut') {
        await moveFileToCurrentFolder(file)
      }
    }

    // 刷新文件列表
    loadFiles()

    // 如果是剪切操作，清空剪贴板
    if (operation === 'cut') {
      clipboardFiles.value = []
      clipboardOperation.value = null
    }

  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('粘贴操作失败')
    }
  }
}

// 快捷键帮助
const showShortcutHelp = () => {
  const helpText = `
键盘快捷键帮助
【①📁 文件操作】：
  Ctrl+U          上传文件
  Ctrl+Shift+N    新建文件夹
  F5 / Ctrl+R     刷新页面
  Ctrl+A          全选文件

【②✏️ 编辑操作】：
  Delete          删除选中项
  F2              重命名选中项
  Ctrl+C          复制选中项
  Ctrl+X          剪切选中项
  Ctrl+V          粘贴到当前文件夹
  F5              刷新文件列表

【③👁️ 预览和下载】：
  Enter / Space   预览选中文件
  Ctrl+D          下载选中文件

【④🔍 导航和视图】：
  Ctrl+F          聚焦搜索框
  Ctrl+B          切换侧边栏显示

【⑤⚡ 通用操作】：
  Esc             清除选择和搜索
  ?               显示此帮助
  `.trim()

  ElMessageBox.alert(helpText, t('filesView.dialogs.shortcutsTitle'), {
    confirmButtonText: t('filesView.dialogs.shortcutsConfirm'),
    type: 'info',
    customStyle: {
      width: '450px',
      fontSize: '14px'
    }
  })
}

// 初始化键盘快捷键
useFileManagerShortcuts({
  onUpload: handleUploadShortcut,
  onCreateFolder: handleCreateFolderShortcut,
  onRefresh: handleRefreshShortcut,
  onSelectAll: handleSelectAllShortcut,
  onDelete: handleDeleteShortcut,
  onCopy: handleCopyShortcut,
  onPaste: handlePasteShortcut,
  onPreview: handlePreviewShortcut,
  onDownload: handleDownloadShortcut,
  onSearch: handleSearchShortcut,
  onToggleView: handleToggleViewShortcut,
  onToggleSidebar: handleToggleSidebarShortcut,
  onEscape: handleEscapeShortcut
})

// 添加额外的快捷键
import { useKeyboardShortcuts } from '../../composables/useKeyboardShortcuts'
useKeyboardShortcuts([
  {
    key: '?',
    handler: showShortcutHelp,
    description: '?: 显示快捷键帮助'
  },
  {
    key: 'F5',
    handler: handleRefresh,
    description: 'F5: 刷新文件列表'
  },
  {
    key: 'F2',
    handler: handleRenameShortcut,
    description: 'F2: 重命名选中的文件或文件夹'
  },
  {
    key: 'x',
    ctrl: true,
    handler: handleCutShortcut,
    description: 'Ctrl+X: 剪切选中的文件或文件夹'
  }
])

// 拖拽相关
const draggedFile = ref<FileInfo | null>(null)

const handleDragStart = (file: FileInfo, event: DragEvent) => {
  console.log('handleDragStart 开始:', {
    fileName: file.originalName,
    fileId: file.id,
    isDirectory: file.isDirectory,
    selectedCount: selectedFiles.value.length
  })

  // 检查当前文件是否在选中列表中
  const isCurrentFileSelected = isFileSelected(file)

  // 确定要拖拽的文件列表
  let filesToDrag: FileInfo[]
  if (isCurrentFileSelected && selectedFiles.value.length > 1) {
    // 如果当前文件在选中列表中且有多个选中文件，拖拽所有选中的文件
    filesToDrag = [...selectedFiles.value]
    console.log('🎯 多选拖拽模式:', filesToDrag.length, '个文件')
  } else {
    // 否则只拖拽当前文件
    filesToDrag = [file]
    // 如果当前文件不在选中列表中，清除其他选择并选中当前文件
    if (!isCurrentFileSelected) {
      selectFile(file, false)
    }
    console.log('🎯 单文件拖拽模式:', file.originalName)
  }

  // 设置拖拽文件（兼容现有逻辑）
  draggedFile.value = file

  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'

    // 传输文件ID列表
    const fileIds = filesToDrag.map(f => f.id)
    event.dataTransfer.setData('text/plain', fileIds.join(','))

    // 传输详细的文件信息
    event.dataTransfer.setData('application/json', JSON.stringify({
      files: filesToDrag.map(f => ({
        id: f.id,
        name: f.originalName,
        isDirectory: f.isDirectory
      })),
      count: filesToDrag.length
    }))
  }

  // 添加拖拽样式
  ;(event.currentTarget as HTMLElement).classList.add('dragging')

  console.log('拖拽开始成功:', filesToDrag.length, '个文件')
  console.log('拖拽文件列表:', filesToDrag.map(f => f.originalName))
}

const handleDragOver = (file: FileInfo, event: DragEvent) => {
  // 只有文件夹可以作为拖拽目标
  if (!file.isDirectory || !draggedFile.value) return
  if (file.id === draggedFile.value.id) return // 不能拖拽到自己

  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }

  // 添加视觉反馈
  ;(event.currentTarget as HTMLElement).classList.add('drag-over')
}

const handleDrop = async (targetFile: FileInfo, event: DragEvent) => {
  console.log('handleDrop 开始:', {
    targetFile: targetFile.originalName,
    draggedFile: draggedFile.value?.originalName || 'null'
  })

  // 移除视觉反馈
  ;(event.currentTarget as HTMLElement).classList.remove('drag-over')

  // 只有文件夹可以作为拖拽目标
  if (!targetFile.isDirectory) {
    ElMessage.warning(t('filesView.messages.dragDropToFolderOnly'))
    return
  }

  // 获取要移动的文件列表
  let filesToMove: FileInfo[] = []

  try {
    // 尝试从dataTransfer获取文件信息
    const fileInfoStr = event.dataTransfer?.getData('application/json')

    if (fileInfoStr) {
      const dragData = JSON.parse(fileInfoStr)
      console.log('解析的拖拽数据:', dragData)

      if (dragData.files && Array.isArray(dragData.files)) {
        // 多文件拖拽
        filesToMove = dragData.files.map((fileInfo: any) => {
          const foundFile = files.value.find(f => f.id === fileInfo.id)
          if (!foundFile) {
            throw new Error(`文件 ${fileInfo.name} 不存在`)
          }
          return foundFile
        })
        console.log('🎯 多文件拖拽模式:', filesToMove.length, '个文件')
      } else if (dragData.id) {
        // 单文件拖拽（兼容旧格式）
        const foundFile = files.value.find(f => f.id === dragData.id)
        if (!foundFile) {
          throw new Error(`文件 ${dragData.name} 不存在`)
        }
        filesToMove = [foundFile]
        console.log('🎯 单文件拖拽模式:', foundFile.originalName)
      }
    } else if (draggedFile.value) {
      // 回退到draggedFile.value
      filesToMove = [draggedFile.value]
      console.log('🎯 回退模式:', draggedFile.value.originalName)
    }

    if (filesToMove.length === 0) {
      throw new Error('无法获取拖拽文件信息')
    }

  } catch (error) {
    console.error('解析拖拽数据失败:', error)
    ElMessage.error(t('filesView.messages.dragDropFailed'))
    return
  }

  // 检查是否有文件试图移动到自己
  const invalidMoves = filesToMove.filter(file => file.id === targetFile.id)
  if (invalidMoves.length > 0) {
    ElMessage.warning(t('filesView.messages.dragDropToSelf'))
    return
  }

  try {
    // 直接执行移动操作，无需确认
    const fileCount = filesToMove.length
    const isMultiple = fileCount > 1

    console.log('开始拖拽移动操作，文件数量:', fileCount, '目标文件夹:', targetFile.originalName)

    // 执行移动操作
    let successCount = 0
    let hasFolder = false

    // 分离文件和文件夹
    const filesToMoveOnly = filesToMove.filter(f => !f.isDirectory)
    const foldersToMove = filesToMove.filter(f => f.isDirectory)

    // 批量移动文件（如果有）
    if (filesToMoveOnly.length > 0) {
      try {
        const fileIds = filesToMoveOnly.map(f => f.id)
        const response = await fileApi.batchMoveFiles({
          fileIds,
          targetParentId: targetFile.id
        })

        const result = response.data
        successCount += result.successCount || 0
        if (result.failureCount > 0) {
          result.errors?.forEach((error: string) => {
            ElMessage.error(error)
          })
        }
      } catch (error) {
        ElMessage.error('批量移动文件失败')
      }
    }

    // 逐个移动文件夹（文件夹移动需要特殊处理）
    for (const sourceFolder of foldersToMove) {
      try {
        console.log('移动文件夹:', sourceFolder.originalName, '到', targetFile.originalName)
        await folderApi.moveFolder(sourceFolder.id, {
          targetParentId: targetFile.id
        })
        hasFolder = true
        successCount++
      } catch (error) {
        console.error(`移动文件夹 ${sourceFolder.originalName} 失败:`, error)
        ElMessage.error(`移动文件夹 "${sourceFolder.originalName}" 失败`)
      }
    }

    // 显示简洁的结果消息
    if (successCount === fileCount) {
      if (isMultiple) {
        ElMessage.success(`已移动 ${successCount} 个项目到 "${targetFile.originalName}"`)
      } else {
        const sourceFile = filesToMove[0]
        ElMessage.success(`已移动 "${sourceFile.originalName}" 到 "${targetFile.originalName}"`)
      }
    } else if (successCount > 0) {
      ElMessage.warning(`部分移动成功：${successCount}/${fileCount} 个项目`)
    }

    // 刷新文件列表和文件夹树
    loadFiles()
    if (hasFolder) {
      folderTreeRef.value?.refreshTree()
    }

    // 清除选择
    clearSelection()

  } catch (error) {
    console.error('移动操作失败:', error)
    ElMessage.error(t('filesView.messages.moveFailed'))
  }
}

const handleDragEnd = (event: DragEvent) => {
  // console.log('handleDragEnd 开始, draggedFile.value:', draggedFile.value?.originalName || 'null')

  // 清除拖拽样式
  ;(event.currentTarget as HTMLElement).classList.remove('dragging')
  // 清除所有拖拽目标样式
  document.querySelectorAll('.drag-over').forEach(el => {
    el.classList.remove('drag-over')
  })

  // 延迟清除draggedFile，给drop事件足够时间执行
  setTimeout(() => {
    console.log('延迟清除 draggedFile.value')
    draggedFile.value = null
  }, 100)
}

// 文件夹树事件处理
const handleFolderTreeClick = (folderId: number) => {
  // 更新当前文件夹ID
  currentFolderId.value = folderId === 0 ? undefined : folderId

  // 更新面包屑导航（异步执行，不阻塞）
  if (currentFolderId.value) {
    getFolderPathAndUpdateBreadcrumbs(currentFolderId.value).catch(() => {
      // 静默处理面包屑更新失败
    })
  } else {
    // 根目录
    breadcrumbs.value = [{ id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined }]
  }

  // 重新加载文件列表
  loadFiles()
}

// 文件夹重命名
const handleFolderRename = async (folderId: number, newName: string) => {
  try {
    await folderApi.renameFolder(folderId, { name: newName })

    // API封装已处理响应状态
    folderTreeRef.value?.refreshTree()
    loadFiles()
    ElMessage.success(t('filesView.messages.folderRenameSuccess'))
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || t('filesView.messages.folderRenameFailed'))
  }
}

// 文件夹删除
const handleFolderDelete = async (folderId: number) => {
  try {
    await folderApi.deleteFolder(folderId)

    // API封装已处理响应状态
    folderTreeRef.value?.refreshTree()
    // 刷新用户信息以更新存储空间
    try {
      await refreshUserStorageInfo()
    } catch (error) {
      // 静默处理存储信息刷新失败
    }
    loadFiles()
    ElMessage.success(t('filesView.messages.folderDeleteSuccess'))
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || t('filesView.messages.folderDeleteFailed'))
  }
}

// 文件夹移动
const handleFolderMove = async (folderId: number, targetParentId: number) => {
  try {
    // 如果目标是根目录(0)，需要特殊处理
    if (targetParentId === 0) {
      // 移动到根目录的逻辑需要后端支持，暂时跳过
      ElMessage.warning('暂不支持移动到根目录')
      return
    }

    await folderApi.moveFolder(folderId, {
      targetParentId: targetParentId
    })

    // API封装已处理响应状态
    folderTreeRef.value?.refreshTree()
    loadFiles()
    ElMessage.success(t('filesView.messages.folderMoveSuccess'))
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || t('filesView.messages.folderMoveOpFailed'))
  }
}





/**
 * 滚动到指定文件并添加高亮效果
 * @param fileId 要高亮的文件ID
 */
const scrollToHighlightFile = (fileId: number) => {
  // console.log('🔍 尝试滚动到文件:', fileId)

  // 查找文件元素
  const fileElement = document.querySelector(`[data-file-id="${fileId}"]`)
  if (fileElement) {
    // console.log('🔍 找到文件元素，开始滚动')
    fileElement.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    })

    // 添加高亮动画
    fileElement.classList.add('file-highlight')

    // 3秒后移除高亮
    setTimeout(() => {
      fileElement.classList.remove('file-highlight')
      highlightFileId.value = null
    }, 3000)
  } else {
    // console.log('🔍 未找到文件元素，可能文件不在当前页面')
  }
}

/**
 * 检查文件是否应该高亮显示
 * @param fileId 文件ID
 * @returns 是否高亮
 */
const isFileHighlighted = (fileId: number) => {
  return highlightFileId.value === fileId
}



// 右键菜单复制
const handleContextCopy = (file: any) => {
  if (file) {
    clipboardFiles.value = [file]
    clipboardOperation.value = 'copy'
    ElMessage.success(t('filesView.messages.copiedToClipboard', { name: file.originalName }))
  }
}

// 右键菜单剪切 - 重构后的简化实现
const handleContextCut = (file: any) => {
  if (file) {
    clipboardFiles.value = [file]
    clipboardOperation.value = 'cut'
    ElMessage.success(t('filesView.messages.cutToClipboard', { name: file.originalName }))
  }
}

// 复制文件到当前文件夹 - 重构后的简化实现
const copyFileToCurrentFolder = async (file: any) => {
  try {
    console.log('复制文件到当前文件夹:', file.originalName)

    if (currentFolderId.value) {
      // 复制到指定文件夹
      await fileApi.copyFileToFolder(file.id, currentFolderId.value)
    } else {
      // 复制到根目录
      await fileApi.copyFileToRoot(file.id)
    }

    // API封装已处理响应状态
    console.log(`文件 "${file.originalName}" 复制成功`)
  } catch (error: any) {
    console.error('复制文件失败:', error)
    ElMessage.error(`复制文件 "${file.originalName}" 失败: ${error.response?.data?.message || error.message}`)
    throw error
  }
}

// 移动文件到当前文件夹 - 重构后的简化实现
const moveFileToCurrentFolder = async (file: any) => {
  try {
    console.log('移动文件到当前文件夹:', file.originalName)

    if (currentFolderId.value) {
      // 移动到指定文件夹
      await fileApi.moveFileToFolder(file.id, currentFolderId.value)
    } else {
      // 移动到根目录
      await fileApi.moveFileToRoot(file.id)
    }

    // API封装已处理响应状态
    console.log(`文件 "${file.originalName}" 移动成功`)
  } catch (error: any) {
    console.error('移动文件失败:', error)
    ElMessage.error(`移动文件 "${file.originalName}" 失败: ${error.response?.data?.message || error.message}`)
    throw error
  }
}



// 路由参数处理
const route = useRoute()

// 刷新用户存储信息
const refreshUserStorageInfo = async () => {
  try {
    // 简单的延迟，让后端有时间更新存储统计
    await new Promise(resolve => setTimeout(resolve, 500))
    console.log('用户存储信息将在下次页面刷新时更新')
  } catch (error) {
    console.warn('刷新用户信息失败:', error)
  }
}

/**
 * 获取文件夹路径信息并更新面包屑
 * @param folderId 文件夹ID
 */
const getFolderPathAndUpdateBreadcrumbs = async (folderId: number) => {
  try {
    // 先设置一个临时的面包屑，避免界面空白
    breadcrumbs.value = [
      { id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined },
      { id: folderId, name: '加载中...', parentId: undefined }
    ]

    const response = await folderApi.getFolderPath(folderId)
    const pathData = response.data

    if (pathData && pathData.breadcrumbs) {
      // 使用后端返回的面包屑数据
      breadcrumbs.value = [
        { id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined },
        ...pathData.breadcrumbs.map(item => ({
          id: item.id,
          name: item.name,
          parentId: undefined // 这个字段在面包屑点击中不使用
        }))
      ]
    } else {
      // 后备方案：只显示当前文件夹
      breadcrumbs.value = [
        { id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined },
        { id: folderId, name: '当前文件夹', parentId: undefined }
      ]
    }

    // console.log('面包屑更新结果:', breadcrumbs.value)
  } catch (error) {
    console.error('获取文件夹路径失败:', error)
    // 错误时显示简化的面包屑
    breadcrumbs.value = [
      { id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined },
      { id: folderId, name: '当前文件夹', parentId: undefined }
    ]
  }
}

/**
 * 组件挂载时处理路由参数
 * 支持搜索、文件夹跳转、文件高亮等功能
 */
onMounted(async () => {
  // 检查路由参数
  const searchParam = route.query.search as string
  const parentIdParam = route.query.parentId as string
  const highlightFileParam = route.query.highlightFile as string

  // console.log('🔍 路由参数:', { searchParam, parentIdParam, highlightFileParam })

  // 处理父文件夹ID参数
  if (parentIdParam) {
    const parentId = parseInt(parentIdParam)
    if (!isNaN(parentId)) {
      // console.log('🔍 设置当前文件夹ID:', parentId)
      // 根目录特殊处理：0 转换为 undefined
      currentFolderId.value = parentId === 0 ? undefined : parentId
      // console.log('🔍 实际设置的文件夹ID:', currentFolderId.value)

      // 获取文件夹路径并更新面包屑
      if (currentFolderId.value) {
        await getFolderPathAndUpdateBreadcrumbs(currentFolderId.value)
      } else {
        // 根目录
        breadcrumbs.value = [{ id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined }]
      }

      // 通知文件夹树组件更新选中状态
      if (folderTreeRef.value) {
        folderTreeRef.value.selectNode(currentFolderId.value || 0)
      }
    }
  }

  // 处理搜索参数
  if (searchParam) {
    // console.log('🔍 检测到全局搜索参数:', searchParam)
    searchKeyword.value = searchParam
    isSearching.value = true
    // 直接执行搜索，不使用防抖
    setTimeout(async () => {
      pagination.value.currentPage = 1
      console.log('🔍 开始执行全局搜索:', searchKeyword.value)
      try {
        await loadFiles()
        // console.log('✅ 全局搜索完成')
      } catch (error) {
        console.error('❌ 搜索失败:', error)
      } finally {
        isSearching.value = false
      }
    }, 100)
  } else {
    setTimeout(() => loadFiles(), 0)
  }

  // 处理文件高亮参数
  if (highlightFileParam) {
    const fileId = parseInt(highlightFileParam)
    if (!isNaN(fileId)) {
      // console.log('🔍 需要高亮文件ID:', fileId)
      highlightFileId.value = fileId
      // 延迟高亮，确保文件列表已加载
      setTimeout(() => {
        scrollToHighlightFile(fileId)
      }, 500)
    }
  }
})

/**
 * 监听路由变化，处理全局搜索和文件夹跳转
 * 支持动态响应路由参数变化
 */
watch(() => route.query, (newQuery) => {
  const searchParam = newQuery.search as string
  const parentIdParam = newQuery.parentId as string
  const highlightFileParam = newQuery.highlightFile as string

  // console.log('🔍 路由变化:', { searchParam, parentIdParam, highlightFileParam })

  // 处理父文件夹ID变化
  if (parentIdParam) {
    const parentId = parseInt(parentIdParam)
    if (!isNaN(parentId)) {
      // 根目录特殊处理：0 转换为 undefined
      const targetFolderId = parentId === 0 ? undefined : parentId

      if (targetFolderId !== currentFolderId.value) {
        // console.log('🔍 文件夹ID变化:', currentFolderId.value, '->', targetFolderId)
        currentFolderId.value = targetFolderId

        // 获取文件夹路径并更新面包屑（异步执行，不阻塞）
        if (currentFolderId.value) {
          getFolderPathAndUpdateBreadcrumbs(currentFolderId.value).catch(error => {
            console.error('更新面包屑失败:', error)
          })
        } else {
          // 根目录
          breadcrumbs.value = [{ id: 0, name: t('filesView.breadcrumbs.root'), parentId: undefined }]
        }

        // 通知文件夹树组件更新选中状态
        if (folderTreeRef.value) {
          folderTreeRef.value.selectNode(currentFolderId.value || 0)
        }

        // 清空搜索关键词，因为要切换到新文件夹
        searchKeyword.value = ''
        pagination.value.currentPage = 1
        loadFiles()
      }
    }
  }

  // 处理搜索参数变化
  if (searchParam && typeof searchParam === 'string') {
    searchKeyword.value = searchParam
    isSearching.value = true
    pagination.value.currentPage = 1
    loadFiles().then(() => {
      isSearching.value = false
    }).catch((error) => {
      console.error('搜索失败:', error)
      isSearching.value = false
    })
  }

  // 处理文件高亮
  if (highlightFileParam) {
    const fileId = parseInt(highlightFileParam)
    if (!isNaN(fileId)) {
      // console.log('🔍 需要高亮文件ID:', fileId)
      highlightFileId.value = fileId
      // 延迟高亮，确保文件列表已加载
      setTimeout(() => {
        scrollToHighlightFile(fileId)
      }, 500)
    }
  }
})
</script>

<style lang="scss" scoped>
.files-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color-primary);
  transition: background-color 0.3s ease;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background-color: var(--bg-color-tertiary);
  border-bottom: 1px solid var(--border-color-light);
  box-shadow: var(--shadow-light);
  transition: all 0.3s ease;

  .header-left, .header-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  flex-shrink: 0;
  background-color: var(--bg-color-tertiary);
  border-right: 1px solid var(--border-color-light);
  transition: all 0.3s ease;

  /* 响应式适配 */
  @media (max-width: 1200px) {
    width: 240px;
  }

  @media (max-width: 992px) {
    width: 200px;
  }

  @media (max-width: 768px) {
    width: 180px;
  }

  @media (max-width: 576px) {
    width: 160px;
  }

  @media (max-width: 480px) {
    width: 140px;
  }
}

.files-container {
  flex: 1;
  background-color: var(--bg-color-secondary);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  &.full-width {
    margin-left: 0;
  }
}

/* 面包屑导航样式 */
.breadcrumb-container {
  padding: 12px 20px;
  background-color: var(--bg-color-tertiary);
  border-bottom: 1px solid var(--border-color-light);
  transition: all 0.3s ease;

  .el-breadcrumb {
    font-size: 14px;

    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        color: var(--el-text-color-regular);

        &.is-link {
          color: var(--el-color-primary);
          cursor: pointer;

          &:hover {
            color: var(--el-color-primary-light-3);
          }
        }
      }

      &:last-child .el-breadcrumb__inner {
        color: var(--el-text-color-primary);
        font-weight: 500;
      }
    }
  }
}

.files-content {
  flex: 1;
  overflow: auto;
  //padding: 20px;
  position: relative;
  user-select: none; /* 防止框选时选中文本 */
}

.files-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, 120px);
  gap: 8px;
  padding: 8px;
  //min-height: 400px;
  position: relative;
  background-color: transparent;
  justify-content: start;
  /* 网格视图滚动条配置 */
  overflow-y: auto;
  overflow-x: hidden;
  max-height: calc(100vh - 200px); /* 自适应高度，预留头部和分页空间 */

  .file-card {
    width: 120px;
    height: 140px;
    background-color: var(--bg-color-tertiary);
    border: 2px solid transparent;
    border-radius: 6px;
    padding: 8px;
    cursor: pointer;
    transition: all 0.15s ease;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    overflow: hidden;

    &:hover {
      border-color: var(--theme-primary);
      // background-color: var(--bg-color-secondary);

      .file-actions {
        opacity: 1;
      }

      .file-icon-container {
        transform: scale(1.05);
      }
    }

    &.selected {
      border-color: var(--theme-primary);
      background-color: var(--theme-primary-bg);

      .file-name {
        color: var(--theme-primary);
        font-weight: 600;
      }

      .file-icon-container .folder-icon,
      .file-icon-container .file-icon {
        color: var(--theme-primary);
      }
    }

    .file-icon-container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 70px;
      transition: transform 0.15s ease;

      .folder-icon {
        font-size: 48px;
        color: #FF9800;
      }

      .file-icon {
        font-size: 40px;
        color: #2196F3;
      }

      // 文件类型特定颜色
      &.folder-preview .folder-icon {
        color: #FF9800;
      }

      &.image-preview .file-icon {
        color: #4CAF50;
      }

      &.video-preview .file-icon {
        color: #9C27B0;
      }

      &.pdf-preview .file-icon {
        color: #F44336;
      }

      &.document-preview .file-icon {
        color: #2196F3;
      }
    }

    .file-name {
      width: 100%;
      font-size: 12px;
      font-weight: 500;
      color: var(--text-color-primary);
      text-align: center;
      line-height: 1.3;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      transition: color 0.15s ease;
      margin-bottom: 4px;
    }

    .file-meta {
      font-size: 10px;
      color: var(--text-color-secondary);
      text-align: center;
      opacity: 0.8;
    }

    &:hover .file-name {
      color: var(--theme-primary);
    }

    .file-actions {
      position: absolute;
      top: 4px;
      right: 4px;
      opacity: 0;
      transition: opacity 0.15s ease;

      .action-buttons {
        display: flex;
        gap: 2px;
        padding: 2px;
        background: var(--bg-color-tertiary);
        backdrop-filter: blur(8px);
        border-radius: 8px;
        box-shadow: var(--shadow-light);
        border: 1px solid var(--border-color-light);

        .el-button {
          width: 20px;
          height: 20px;
          border: none;
          background: transparent;
          color: var(--text-color-secondary);
          transition: all 0.15s ease;
          font-size: 12px;
          border-radius: 4px;
          padding: 0;

          &:hover {
            background: var(--theme-primary);
            color: white;
          }

          &.favorited {
            color: #FF9800;

            &:hover {
              background: #FF9800;
              color: white;
            }
          }
        }
      }
    }
  }
  
  .empty-state {
    grid-column: 1 / -1;
    text-align: center;
    padding: 80px 20px;
    background-color: var(--bg-color-tertiary);
    border-radius: 12px;
    border: 2px dashed var(--border-color-base);
    margin: 20px;
    transition: all 0.3s ease;

    .empty-icon {
      font-size: 64px;
      margin-bottom: 16px;
      color: var(--text-color-tertiary);
      transition: color 0.3s ease;
    }

    p {
      margin: 0 0 20px 0;
      font-size: 16px;
      color: var(--text-color-secondary);
      font-weight: 500;
      transition: color 0.3s ease;
    }
  }
}

.files-list {
  // margin: 16px;
  background-color: var(--bg-color);
  // border-radius: 8px;
  // box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 400px;
  position: relative;
  /* 列表视图滚动条配置 */
  max-height: calc(100vh - 200px); /* 自适应高度，预留头部和分页空间 */
  display: flex;
  flex-direction: column;

  .list-header {
    display: grid;
    grid-template-columns: 50px 1fr 100px 120px 120px;
    background-color: var(--bg-color-secondary);
    border-bottom: 1px solid var(--border-color-light);
    padding: 12px 16px;
    font-weight: 500;
    font-size: 13px;
    color: var(--text-color-secondary);
    cursor: pointer;
    min-height: 44px;

    .header-cell {
      display: flex;
      align-items: center;

      &.name-cell {
        padding-left: 8px;
      }
    }
  }

  .list-body {
    min-height: 300px;
    position: relative;
    /* 列表主体滚动配置 */
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;

    .list-empty-space {
      height: 300px;
      width: 100%;
      cursor: pointer;
      background: transparent;
    }

    .list-row {
      display: grid;
      grid-template-columns: 50px 1fr 100px 120px 120px;
      padding: 8px 16px;
      border-bottom: 1px solid var(--border-color-lighter);
      cursor: pointer;
      transition: background-color 0.15s ease;
      min-height: 48px;
      background-color: var(--bg-color);

      &:hover {
        background-color: var(--bg-color-secondary);

        .list-actions {
          opacity: 1;
        }
      }

      &.selected {
        background-color: var(--theme-primary-bg);
        border-left: 2px solid var(--theme-primary);

        .file-name {
          color: var(--theme-primary);
          font-weight: 600;
        }

        .folder-icon, .file-icon {
          color: var(--theme-primary);
        }
      }

      &:last-child {
        border-bottom: none;
      }

      .row-cell {
        display: flex;
        align-items: center;

        &.icon-cell {
          justify-content: center;

          .file-icon-wrapper {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;

            .folder-icon {
              font-size: 20px;
              color: #FF9800;
            }

            .file-icon {
              font-size: 18px;
            }

            &.folder-preview .folder-icon {
              color: #FF9800;
            }

            &.image-preview .file-icon {
              color: #4CAF50;
            }

            &.video-preview .file-icon {
              color: #9C27B0;
            }

            &.pdf-preview .file-icon {
              color: #F44336;
            }

            &.document-preview .file-icon {
              color: #2196F3;
            }
          }
        }

        &.name-cell {
          padding-left: 8px;

          .file-name {
            font-weight: 500;
            color: var(--text-color-primary);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            transition: color 0.3s ease;
          }
        }

        &.size-cell {
          .file-size-badge {
            color: var(--text-color-secondary);
            font-size: 12px;
            font-weight: 400;
          }

          .folder-indicator {
            color: var(--text-color-secondary);
            font-size: 12px;
          }
        }

        &.date-cell {
          .file-date {
            color: var(--text-color-secondary);
            font-size: 13px;
            transition: color 0.3s ease;
          }
        }

        &.actions-cell {
          justify-content: center;

          .list-actions {
            display: flex;
            gap: 4px;
            opacity: 0.6;
            transition: opacity 0.15s ease;

            .el-button {
              padding: 4px 8px;
              font-size: 12px;
              border: none;
              background: transparent;
              color: var(--text-color-secondary);
              border-radius: 4px;

              &:hover {
                background: var(--theme-primary);
                color: white;
              }

              &.favorited {
                color: #FF9800;

                &:hover {
                  background: #FF9800;
                  color: white;
                }
              }
            }
          }
        }
      }
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px 20px;
  background-color: var(--bg-color-tertiary);
  border-top: 1px solid var(--border-color-light);
  flex-shrink: 0; /* 防止被压缩 */
  position: sticky;
  bottom: 0;
  z-index: 10;
  transition: all 0.3s ease;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 16px;

    .header-right {
      justify-content: space-between;
    }
  }

  .files-grid {
    grid-template-columns: repeat(auto-fill, 100px);
    gap: 8px;
    padding: 8px;
    justify-content: start;

    .file-card {
      width: 100px;
      height: 120px;
      padding: 6px;
      border-radius: 4px;

      .file-icon-container {
        height: 60px;

        .folder-icon {
          font-size: 32px;
        }

        .file-icon {
          font-size: 28px;
        }
      }

      .file-name {
        font-size: 11px;
        line-height: 1.2;
      }

      .file-meta {
        font-size: 9px;
      }

      .file-actions .action-buttons {
        padding: 2px;

        .el-button {
          width: 16px;
          height: 16px;
          font-size: 10px;
        }
      }
    }
  }

  .files-list {
    margin: 16px;
  }
}

/* 临时文件夹树样式 */
.folder-tree {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tree-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  border-bottom: 1px solid var(--border-color-light);
  background-color: var(--bg-color-secondary);
  transition: all 0.3s ease;
}

.tree-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color-primary);
  transition: color 0.3s ease;
}

.tree-content {
  flex: 1;
  padding: 8px;
  background-color: transparent;
}

.tree-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  color: var(--text-color-primary);
}

.tree-item:hover {
  background-color: var(--bg-color-secondary);
}

.tree-item.root-item {
  font-weight: 600;
  color: var(--theme-primary);
}

.tree-placeholder {
  padding: 20px;
  text-align: center;
  color: var(--text-color-secondary);
  font-size: 14px;
  transition: color 0.3s ease;
}

.tree-placeholder p {
  margin: 8px 0;
}

/* 拖拽样式 */
.file-card[draggable="true"] {
  cursor: move;
  transition: all 0.2s ease;
}

.file-card[draggable="true"]:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.file-card.drag-over {
  border: 2px dashed #409eff !important;
  background-color: #ecf5ff !important;
  transform: scale(1.02);
}

.file-card:global(.dragging) {
  opacity: 0.6;
  transform: rotate(3deg) scale(0.95);
}

/* 快捷键帮助样式 */
:global(.el-message-box__content) {
  kbd {
    display: inline-block;
    padding: 2px 6px;
    font-size: 11px;
    line-height: 1.4;
    color: #444;
    background-color: #fafbfc;
    border: 1px solid #d1d5da;
    border-radius: 3px;
    box-shadow: inset 0 -1px 0 #d1d5da;
    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
    margin: 0 2px;
  }

  p {
    margin: 4px 0;
    line-height: 1.5;
  }

  h4 {
    margin: 12px 0 6px 0;
    font-weight: 600;
  }
}


/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: var(--bg-color-tertiary);
  border: 1px solid var(--border-color-light);
  border-radius: 8px;
  box-shadow: var(--shadow-base);
  padding: 8px 0;
  z-index: 99999;
  min-width: 120px;
  max-width: 200px;
  pointer-events: auto;
  transition: all 0.3s ease;
}

.context-menu-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: var(--text-color-primary);
  transition: all 0.2s ease;

  &:hover {
    background-color: var(--bg-color-secondary);
  }

  &.danger {
    color: var(--color-danger);

    &:hover {
      background-color: rgba(239, 68, 68, 0.1);
    }
  }

  .el-icon {
    margin-right: 8px;
    font-size: 16px;
  }
}

.context-menu-divider {
  height: 1px;
  background-color: var(--border-color-light);
  margin: 4px 0;
  transition: background-color 0.3s ease;
}

/* 文件高亮样式 */
.file-highlight {
  animation: highlight-pulse 2s ease-in-out;
  border: 2px solid var(--el-color-primary) !important;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.3) !important;
}

@keyframes highlight-pulse {
  0% {
    background-color: rgba(64, 158, 255, 0.1);
    transform: scale(1);
  }
  50% {
    background-color: rgba(64, 158, 255, 0.2);
    transform: scale(1.02);
  }
  100% {
    background-color: rgba(64, 158, 255, 0.1);
    transform: scale(1);
  }
}

/* 网格视图中的高亮效果 */
.file-card.file-highlight {
  border-radius: 8px;
}

/* 列表视图中的高亮效果 */
.list-row.file-highlight {
  border-radius: 4px;
}

/* 自定义滚动条样式 - 网格和列表视图通用 */
.files-grid::-webkit-scrollbar,
.list-body::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.files-grid::-webkit-scrollbar-track,
.list-body::-webkit-scrollbar-track {
  background: var(--bg-color-secondary);
  border-radius: 4px;
}

.files-grid::-webkit-scrollbar-thumb,
.list-body::-webkit-scrollbar-thumb {
  background: var(--border-color-light);
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.files-grid::-webkit-scrollbar-thumb:hover,
.list-body::-webkit-scrollbar-thumb:hover {
  background: var(--theme-primary);
}

/* Firefox 滚动条样式 */
.files-grid,
.list-body {
  scrollbar-width: thin;
  scrollbar-color: var(--border-color-light) var(--bg-color-secondary);
}
</style>
